<?php
/**
 * Front Controller plug in to set up the view with the Places view helper
 * path and some useful request variables.
 *
 */
class Wmp_Controller_Plugin_ViewSetup extends Zend_Controller_Plugin_Abstract
{    
    /**
     * @var Zend_View
     */
    protected $_view;    
    protected $_layoutName;
        
    public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
    {
       	$config = Zend_Registry::get('config');
    	$moduleConfigSession = new Zend_Session_Namespace('moduleConfig');
    	
    	$defaultNamespace = new Zend_Session_Namespace('Default');
    	if($request->getParam('region')){
			$currentRegion = $request->getParam('region');    		
    	}else {
    		if(isset($defaultNamespace->region)){
    			$currentRegion = $defaultNamespace->region; 
    		}
    		else {
    			$currentRegion = $config->default->region;
    		}
    	}
    	
    	if($request->getParam('language')){
			$currentLanguage = $request->getParam('language');    		
    	}else {
    		if(isset($defaultNamespace->language)){
    			$currentLanguage = $defaultNamespace->language; 
    		}
    		else {
    			$currentLanguage = $config->default->language;
    		}
    	}
    	
    	$defaultNamespace->language = $currentLanguage;
    	$defaultNamespace->region = $currentRegion;		
    	
       	$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
        $viewRenderer->init();
        $viewRenderer->setViewSuffix($config->views->suffix);        
        $view = $viewRenderer->view;
        $this->_view = $view;    
        
        //Zend_Debug::dump($request); exit(1);
        
        // set up common variables for the view
        $view->module = $request->getModuleName();
        $view->controller = $request->getControllerName();
        $view->action = $request->getActionName();
        
               
        $moduleTable = new Wmp_Model_ModulesTable();
        $moduleTable = $moduleTable->find($request->getModuleName())->current();
    	
        //TODO : pour optimiser le code, je devrais traiter ça en premier
                	
    	//repertoir de template affecté à la région
    	$regions = new Wmp_Db_Table_Regions();
    	$region = $regions->find($request->getParam('region'))->current();	
    	$registredTemplate = $region->template;
    	  
    	//si aucun repertoire enregistré en bdd, alors je prend celui
    	//enregistre dans le fichier de config
       	if(!$registredTemplate) $registredTemplate = $config->defaultTemplate;      
    	
    	$actionParams = new Wmp_Model_ActionparamsTable();
    	$actionParams = $actionParams->getRow($view->module , $view->controller , $view->action);        
   	
       	$layoutName = "layout_site_default";//layout par defaut
    	$layoutsDir = $config->path->public->dir.'/templates/'.$registredTemplate.'/layouts';
    	$actionLayout =  $layoutsDir.'/layout_'.$view->module.'_'.$view->controller.'_'.$view->action.
	    										'.'.$config->layouts->suffix;
    	if (file_exists($actionLayout)) {
	    	     $layoutName = 'layout_action_'.$view->action;
	    } else {
	    	$controllerLayout =  $layoutsDir.'/layout_'.$view->module.'_'.$view->controller.
	    										'.'.$config->layouts->suffix;
		    if (file_exists($controllerLayout)) {
	    	     $layoutName = 'layout_controller_'.$view->controller;
	   		} else {
	   			$moduleLayout =  $layoutsDir.'/layout_'.$view->module.'.'.$config->layouts->suffix;
	   			if (file_exists($moduleLayout)) {
	    	     $layoutName = 'layout_'.$view->module;
	   			} 		
	   		}
	    }

	    $skin = $region->skin;
	    if(!$skin) $skin = "skin_default";
    	    		
    	//saving in the registry
    	Zend_Registry::set('template', $registredTemplate);//repertoire de template
    	Zend_Registry::set('layoutName', $layoutName);//layout utilisé
    	Zend_Registry::set('skin', $skin);//layout utilisé
		Zend_Registry::set('module', $view->module);
		Zend_Registry::set('controller', $view->controller); 
		Zend_Registry::set('action', $view->action);
		Zend_Registry::set('region', $currentRegion);
		Zend_Registry::set('language', $currentLanguage);
		
		
		// set up doctype for any view helpers that use it
        $view->doctype('XHTML1_STRICT');
         
		/*--------------------------------------------------------------------------
		 * Définition des chemins de view/helper:
		 * les views helpers peuvent être définies dans deux endroits:
		 * -Soit dans le modules/views/helpers/ (en priorité)
		 * -Soit dans library/Wmp/View/Helper
		 */
        // add helper path to Wmp/View/Helper directory within this library
        $prefix = 'Wmp_View_Helper';
        $dir = dirname(__FILE__) . '/../../View/Helper'; //repertoir relatif : Wmp/View/Helper     
        $view->addHelperPath($dir, $prefix);
		
		// ajout des helpers spécifique au module en cours
		//Permet de vérifier la présence d'une view_helper en priorité dans le module
		//Ensuite dans Wmp_View, et Zend_View
		$prefix = $view->module.'_View_Helper';
        $dir =$config->path->modules->dir. '/'.$view->module.'/views/helpers';   
		$view->addHelperPath($dir, $prefix);
		
		//chemins des templates .phtml(ou .tpl) de modules
		$moduleTemplateScripts=$config->path->public->dir.'/templates/default/modulestemplates/'.$view->module;
		$view->addScriptPath($moduleTemplateScripts);
		if($registredTemplate!='default') {
			$moduleTemplateScripts=$config->path->public->dir.'/templates/'.$registredTemplate.'/modulestemplates/'.$view->module;
			$view->addScriptPath($moduleTemplateScripts);			
		}				
		//Zend_Debug::dump($view); exit(1);
		//$view->render('index/index.phtml');
		/*---------------------------------------------------------------------------*/
		
		/*************Activation de ajax, et dojo************************************/
		//IMPORTANT : add dojo path befor jquery path, pour eviter une erreur...
		$view->addHelperPath('Zend/Dojo/View/Helper/', 'Zend_Dojo_View_Helper');
		$view->addHelperPath("ZendX/JQuery/View/Helper", "ZendX_JQuery_View_Helper");
		ZendX_JQuery_View_Helper_JQuery::enableNoConflictMode(); 
		/************************Fin activation de ajax, jquery et dojo**********************/
		
        // setup initial head wmp holders, metadata
        $view->headMeta()->appendHttpEquiv('Content-Type', 'text/html;charset='.Zend_Registry::get('config')->charset);
		
        if(isset($moduleTable->config))
        $moduleconfig = unserialize(base64_decode($moduleTable->config));
        
		//URGENT : à optimiser, parametrer les priorités : action, controller, module, default
		if(isset($moduleconfig->title))
			$view->title=$moduleconfig->title;
			
		if(isset($moduleconfig->copyright))	
        	$view->layout()->copyright=$moduleconfig->copyright;//TODO sinon copyright de config.in
		if(isset($actionParams->metakeywords))
        	$view->headMeta()->appendName('keywords', $view->WmpTranslate($actionParams->metakeywords));
        else if(isset($moduleTable->metakeywords))
        	$view->headMeta()->appendName('keywords', $view->WmpTranslate($moduleTable->metakeywords));
        else {
        	//$view->headMeta()->appendName('keywords', $view->WmpTranslate($config->meta->keywords));
        	//TODO : Tester si $moduleconfig->description non nul, sinon $config->meta->description
        	if(isset($moduleconfig->keywords))
        		$view->headMeta()->appendName('keywords', $view->WmpTranslate($moduleconfig->keywords));
        }
        	
        if(isset($actionParams->metadescription))
        	$view->headMeta()->appendName('description', $view->WmpTranslate($actionParams->metadescription));
        else if(isset($moduleTable->metadescription))
        	$view->headMeta()->appendName('description', $view->WmpTranslate($moduleTable->metadescription));
        else{
        	//$view->headMeta()->appendName('description', $config->meta->description);
        	//TODO : Tester si $moduleconfig->description non nul, sinon $config->meta->description
        	if(isset($moduleconfig->description))
        		$view->headMeta()->appendName('description', $view->WmpTranslate($moduleconfig->description));
        }
        
        $view->headScript()->captureStart();
       	echo  "baseUrl = '".$view->baseUrl()."'";
        $view->headScript()->captureEnd(); 
    }
    
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        $config = Zend_Registry::get('config');
        $registredTemplate=Zend_Registry::get('template');
    	$this->_controllerCssLink($request);
        $view = $this->_view;
        $moduleTemplateScripts=$config->path->public->dir.'/templates/'.$registredTemplate.'/modulestemplates/'.$view->module;
        $view->addScriptPath($moduleTemplateScripts);        
    }
    
    public function postDispatch(Zend_Controller_Request_Abstract $request)
    {
        $config = Zend_Registry::get('config');
    	if (!$request->isDispatched()) {
            return;
        }
        $view = $this->_view;
        
		/*
		 * S'il n'y a pas de headTittle dans l'action du controlleur
		 * alors, on affecte la valeur title au headTitle
		 */
        if (count($view->headTitle()->getValue()) == 0) {
            $view->headTitle($view->title);
            $view->layout()->title=$view->title;
        }
        //URGENT : faire un else, et prendre en compte un titre stoqué dans config.region.default.title="..."
        
        //ajoute -Wmp dans le headTitle
        $view->headTitle()->setSeparator(' - ');		
        $view->headTitle(Zend_Registry::get('config')->site->title);  

        //Log action in databases
		$view->WmpLog();		
		$moduleTemplateScripts=$config->path->public->dir.'/templates/default/modulestemplates/'.$view->module;
		$view->addScriptPath($moduleTemplateScripts);
        
    }
    
    protected function _controllerCssLink(Zend_Controller_Request_Http $request)
    {
        $config = Zend_Registry::get('config');
    	$view = $this->_view;
        $action = Zend_Registry::get('action');
    	$controller = Zend_Registry::get('controller');
        $module = Zend_Registry::get('module');		
        $ModuleTemplate = Zend_Registry::get('template');          

  
        $template_path = '/templates/'.$ModuleTemplate.'/css';
        $local_path = $template_path.'/'.$request->getParam('language');
        $module_path = $local_path . '/' . $module;        
		//URGENT : à ajouter
		//www/templates/le nom du template/css/le nom du module.css
		//www/templates/le nom du template/css/'controller.'le nom du controlleur.css
		
        $regions = new Wmp_Db_Table_Regions();
        $region = $regions->find($request->getParam('region'));
        //$template(isset($region->template))
        $cssList = array(
				        'site_css'=>'/css/default',
        				'template_css' => $template_path.'/template',	
						'skin_css' => $template_path.'/'.Zend_Registry::get('skin'),		
						'local_css' => $local_path .'/local',
						'module_css' =>  $module_path.'/module',
						'module_controller_css' => $module_path.'/controller.'.$controller
					);
		$this->_addCss( $cssList );
		$this->_addCss( $cssList, "print" );		
    }
    
	private function _addCss($cssArray,$type="screen,projection")
    {
    	$config = Zend_Registry::get('config');
    	$extension =".css";
    	
    	if($type=="print") $extension=".print.css";  	
    	
    	foreach($cssArray as $key=>$val){
	    	$cssfile = $val.$extension;    		
	    	if (file_exists($config->path->public->dir.$cssfile)) {
	    		
	            $url = $this->_view->baseUrl().$cssfile;        
	            $this->_view->headLink()->appendStylesheet($url , $type);
	       	}
    	}    	
    }
}